package com.zxq.large_link_app;


import android.Manifest;
import android.os.*;
import android.util.*;
import android.view.*;
import android.webkit.*;
import android.widget.*;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;


import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.zxq.large_link_app.enity.IotPlatform;
import com.zxq.large_link_app.enity.LocationInfo;
import com.zxq.large_link_app.enity.NavMapEntity;
import com.zxq.large_link_app.http.HttpAddProject;
import com.zxq.large_link_app.http.HttpSwitchPlatform;
import com.zxq.large_link_app.map.NavigationMap;
import com.zxq.large_link_app.poup.CustomEditTextBottomPopup;
import com.zxq.large_link_app.sp.SpDBLite;
import com.zxq.large_link_app.web.WebClient;
import java.util.*;
import java.util.concurrent.*;

import io.reactivex.rxjava3.functions.Consumer;

public class MainActivity extends AppCompatActivity implements OnOptionPickedListener, View.OnClickListener {

    String lng;
    String lat;

    OptionPicker navPicker = null,platformPicker = null;


    /**
     * 平台数据
     */
    List<IotPlatform> iotPlatformList = new ArrayList<>();


    /**
     * h5页面
     */
    WebView h5Web;
    ImageView btnPlus;
    CustomEditTextBottomPopup textBottomPopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocationClient.setAgreePrivacy(true);
        setContentView(R.layout.activity_main);
        h5Web = findViewById(R.id.h5Web);
        btnPlus = findViewById(R.id.project_plus);
        textBottomPopup = new CustomEditTextBottomPopup(MainActivity.this);
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Throwable {
                if(aBoolean) {
                    initBdLocation();
                    mLocationClient.start();
                }
            }
        });
        initBdLocation();
        initWebConfig();
        initNavPicker();
        initPlatformPicker();

        findViewById(R.id.config_image).setOnClickListener(this);
        findViewById(R.id.project_plus).setOnClickListener(this);
        HttpSwitchPlatform.setISwitchPlatformListener(HttpAddProject.getInstance());
    }


    public LocationClient mLocationClient = null;

    /**
     * 初始化百度位置
     */
    private void initBdLocation() {
        try {
            mLocationClient = new LocationClient(getApplicationContext());
            //声明LocationClient类
            mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
                @Override
                public void onReceiveLocation(BDLocation location) {
                    LocationInfo.location = location;
                    Log.e("bdLocation:",location.toString());
                }
            });
            LocationClientOption option = new LocationClientOption();


            option.setIsNeedAddress(true);
//可选，是否需要地址信息，默认为不需要，即参数为false
//如果开发者需要获得当前点的地址信息，此处必须为true

            option.setNeedNewVersionRgc(true);
//可选，设置是否需要最新版本的地址信息。默认需要，即参数为true

            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
            option.setCoorType("bd09ll");
            option.setFirstLocType(LocationClientOption.FirstLocType.ACCURACY_IN_FIRST_LOC);
            option.setScanSpan(10000);
            option.setOpenGps(true);
            option.setLocationNotify(true);
            option.setIgnoreKillProcess(false);
            option.SetIgnoreCacheException(false);
            option.setWifiCacheTimeOut(5*60*1000);
            option.setEnableSimulateGps(false);
            option.setNeedNewVersionRgc(true);
            mLocationClient.setLocOption(option);
        } catch (Exception e) {
            Log.e("baidu_location",e.toString());
        }

    }




    /**
     * 初始化web配置
     */
    private void initWebConfig() {
        WebSettings mWebSettings = h5Web.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setDomStorageEnabled(true);
        WebClient webClient = new WebClient(MainActivity.this);
        h5Web.setWebViewClient(webClient);
        h5Web.addJavascriptInterface(this,"$App");
        h5Web.loadUrl(SpDBLite.getObj().getH5Url());
    }

    /**
     * 初始化导航选择框
     */
    private void initNavPicker() {
        navPicker = new OptionPicker(this);
        navPicker.setTitle("请选择导航地图");
        navPicker.setBodyWidth(140);
        navPicker.setData(NavMapEntity.getDisplayMap());
        navPicker.setDefaultPosition(2);
        navPicker.setOnOptionPickedListener(this);
    }

    /**
     * 初始化平台选择器
     */
    private void initPlatformPicker() {
        platformPicker = new OptionPicker(this);
        platformPicker.setTitle("请选择平台");
        platformPicker.setBodyWidth(300);
        platformPicker.setData(iotPlatformList);
        platformPicker.setDefaultPosition(2);
        platformPicker.setOnOptionPickedListener(new OnOptionPickedListener() {
            @Override
            public void onOptionPicked(int position, Object item) {
                IotPlatform selectCompany = (IotPlatform) item;
                h5Web.loadUrl(selectCompany.getH5Url());
                if(HttpSwitchPlatform.getISwitchPlatformListener() != null) {
                    String webUrl =  selectCompany.getWebUrl();
                    HttpSwitchPlatform.getISwitchPlatformListener().notifyPlatformSwitch(webUrl);
                }
            }
        });

    }



    /**
     * 接收vue的数据
     */
    @JavascriptInterface
    public void getDataFormVue(String msg) {
        lng = msg.split(":")[1];
        lat = msg.split(":")[2];
        Log.e("lng:", lng);
        Log.e("lat:", lat);
        if(navPicker  != null) {
            handler.sendEmptyMessage(0x01);
        }
    }

    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0x01) {
                navPicker.show();
            }
            if(msg.what == 0x02) {

                platformPicker.show();
            }
        }
    };


    @Override
    public void onOptionPicked(int position, Object item) {
        if(position == 0) {
            NavigationMap.skipToBdMap(this,lng,lat);
        }
        if(position == 1) {
            NavigationMap.skipToGdMap(this,lng,lat);
        }
    }


    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(1,2,0L, TimeUnit.SECONDS,new ArrayBlockingQueue(3));

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.config_image:{
                poolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        iotPlatformList.clear();
                        List<IotPlatform> rstData = HttpSwitchPlatform.getTotalPlatformMessage();
                        iotPlatformList.addAll(rstData);
                        handler.sendEmptyMessage(0x02);
                    }
                });
            }
            break;
            case R.id.project_plus:{
                new XPopup.Builder(MainActivity.this)
                        .autoOpenSoftInput(true)
                        .autoFocusEditText(true)
                        .setPopupCallback(new SimpleCallback(){
                            @Override
                            public void onDismiss(BasePopupView popupView) {
                                super.onDismiss(popupView);
                                h5Web.reload();
                            }
                        })
                        .asCustom(textBottomPopup)
                        .show();
            }
            break;

        }



    }



}